﻿using ERPSystem.Common.Domains.Notices;
using ERPSystem.Common.DTO;
using ERPSystem.Enum.CommonErrorCodes;
using MediatR;
using Newtonsoft.Json;
using SqlSugar;

namespace SalesManagementCommon.API.SalesManagementCommons.BillingInvoicing
{
    public class BillingInvoiceQueryHander : IRequestHandler<BillingInvoiceQueryCommand, Result<PageResultDto<BillNoticesDTO>>>
    {
        private readonly ISqlSugarClient db;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db"></param>

        public BillingInvoiceQueryHander(ISqlSugarClient db)
        {
            this.db = db;
        }
       

        /// <summary>
        /// 开票通知单显示查询
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result<PageResultDto<BillNoticesDTO>>> Handle(BillingInvoiceQueryCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<PageResultDto<BillNoticesDTO>>();
            var page = new PageResultDto<BillNoticesDTO>() { TotalCount = 0, TotalPage = 0, List = new List<BillNoticesDTO>() };
            try
            {
                RefAsync<int> totalCount = 0;
                RefAsync<int> totalPage = 0;
                var list = db.Queryable<Billingmaterial, Invoicingmemo>((b, bv) => b.ItemBianma == bv.ItemBianma).Select((b, bv) => new BillNoticesDTO()
                {
                    SaleordersNumber = b.SaleordersNumber,//销售订单号
                    BillingName = b.BillingName,//开票名称
                    BillingmaterialId = b.BillingmaterialId,//序号
                    Documentsnumber = bv.Documentsnumber,//单据编码
                    DocumentsDate = bv.DocumentsDate,//单据日期
                    Documentstatus = bv.Documentstatus,//单据状态
                    BusinessTypeId = bv.BusinessTypeId,//业务类型
                    ClientName = bv.ClientName,//客户名称
                    MaterialName = b.MaterialName,//物料名称
                    ItemBianma = bv.ItemBianma,//物料编码
                    BillingNumber = b.BillingNumber,//数量
                    BillingPrice = b.BillingPrice,//单价
                    BillingSum = b.BillingSum,//金额
                }).MergeTable();

                //var list = db.Queryable<Billingmaterial>()
                //    .LeftJoin<Invoicingmemo>((b, bv) => b.ItemBianma == bv.ItemBianma)
                //    .Select((b, bv) => new BillNoticesDTO
                //    {
                //        BillingmaterialId = b.BillingmaterialId,//序号
                //        Documentencoding = b.Documentencoding,//单据编码
                //        DocumentsDate = bv.DocumentsDate,//单据日期
                //        Documentstatus = bv.Documentstatus,//单据状态
                //        BusinessTypeId = bv.BusinessTypeId,//业务类型
                //        ClientName = bv.ClientName,//客户名称
                //        MaterialName = b.MaterialName,//物料名称
                //        ItemBianma = bv.ItemBianma,//物料编码
                //        BillingNumber = b.BillingNumber,//数量
                //        BillingPrice = b.BillingPrice,//单价
                //        BillingSum = b.BillingSum,//金额
                //    }).MergeTable();
                //var abc=list.ToList();


                if (!string.IsNullOrEmpty(request.SaleordersNumber))// 销售订单号
                {
                    list = list.Where(b => b.SaleordersNumber.Contains(request.SaleordersNumber));
                }
                if (!string.IsNullOrEmpty(request.ClientName))// 客户名称
                {
                    list = list.Where(bv=>bv.ClientName.Contains(request.ClientName));
                }
                if (!string.IsNullOrEmpty(request.BillingName))// 开票名称
                {
                    list = list.Where(b => b.BillingName.Contains(request.BillingName));
                }
                var res = await list.ToPageListAsync(request.PageIndex, request.PageSize, totalCount, totalPage);
                page.TotalCount = totalCount;
                page.TotalPage = totalPage;
                page.List = JsonConvert.DeserializeObject<List<BillNoticesDTO>>(JsonConvert.SerializeObject(res));
                if (page.List.Any())
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = page;
                    result.Msg = "获取当前条件下开票通知单信息成功！";
                }
                else
                {
                    result.Data = new PageResultDto<BillNoticesDTO>() { List = new List<BillNoticesDTO>() };
                }
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
